package com.yy.sso.gateway.com.yy.sso.gatweway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

/**
 * 全局拦截器
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 需要跳过的url
     */
    private String[] skipUrls = {"/auth/oauth/token", "/auth/oauth/authorize"};

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();

        /**
         * 设置url白名单
         */
        if (Arrays.asList(skipUrls).contains(url)) {
            return chain.filter(exchange);
        }

        /**
         * 校验认证信息
         */
        String token = request.getHeaders().getFirst("Authorization");
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if (!(authentication instanceof OAuth2Authentication)) {
//            return null;
//        }
//        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
//        Object principal = oAuth2Authentication.getPrincipal();
//        List<String> authorities = new ArrayList<>();
//        authentication.getAuthorities().forEach(item -> authorities.add(item.getAuthority()));
        if (token == null || token.isEmpty()) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //添加header信息，主要放了用户信息和权限信息
//        JSONObject object = new JSONObject();
//        object.put("principal", principal);
//        object.put("authorities", authorities);
//        ServerHttpRequest accessTokenRequest = request.mutate().headers(httpHeaders -> httpHeaders.add("access_oken", JSON.toJSONString(object))).build();
//        ServerWebExchange build = exchange.mutate().request(accessTokenRequest).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
